package com.abss.vote.job;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@Configuration
@EnableScheduling
@EnableAsync
public class ActivityCronJob {

	Logger log = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Async
	@Scheduled(cron = "0 0 * * * ?")
	public void checkActivity() {
		log.info("开始核查活动是否结束的定时任务...");
		try {
			String sql = "select activity_id,activity_endtime,activity_state from activity where activity_state<>2";
			String updateSql = "update activity set activity_state = ? where activity_id = ?";
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
			for (Map<String, Object> map : list) {
				String activityId = map.get("activity_id") + "";
				String activityEndTime = map.get("activity_endtime") + "";
				Date endTime = format.parse(activityEndTime);
				Date now = new Date();
				if (now.after(endTime)) {
					log.info("当前时间晚于结束时间，更新活动状态，活动ID是："+activityId);
					jdbcTemplate.update(updateSql, 2, activityId);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		System.out.println("开始");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String activityEndTime = "2025-09-02 19:24:59.000";
		try {
			Date endTime = format.parse(activityEndTime);
			Date now = new Date();
			if (now.after(endTime)) {
				System.out.println("当前时间晚于结束时间，更新活动状态");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
